<template>
  <div class="freight-rule-detail">
    <el-card>
      <template #header>
        <div style="display: flex; align-items: center; justify-content: space-between;">
          <div style="display: flex; align-items: center; gap: 12px;">
            <el-button @click="goBack" type="primary" plain size="small">
              <el-icon><ArrowLeft /></el-icon>
              返回列表
            </el-button>
            <h3 style="margin: 0;">物流规则详情</h3>
          </div>
          <div>
            <el-button @click="editRule" type="primary" size="small">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
          </div>
        </div>
      </template>

      <div v-if="ruleDetail" class="detail-content">
        <!-- 基本信息 -->
        <el-row :gutter="24">
          <el-col :span="12">
            <div class="info-section">
              <h4>基本信息</h4>
              <el-descriptions :column="1" border>
                <el-descriptions-item label="物流名称">
                  <div style="display: flex; align-items: center; gap: 8px;">
                    <el-avatar v-if="ruleDetail.logoUrl" :src="ruleDetail.logoUrl" :size="32" shape="square" />
                    <el-avatar v-else :size="32" shape="square" style="background-color: #f5f7fa; color: #909399;">
                      <el-icon><Box /></el-icon>
                    </el-avatar>
                    <span>{{ ruleDetail.logisticsName || '未设置' }}</span>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="物流方式">
                  {{ ruleDetail.logisticsType }}
                </el-descriptions-item>
                <el-descriptions-item label="物流速度">
                  {{ ruleDetail.speed || '未设置' }}
                </el-descriptions-item>
                <el-descriptions-item label="重量限制">
                  {{ ruleDetail.weightLimit }}G
                </el-descriptions-item>
                <el-descriptions-item label="税号">
                  {{ ruleDetail.taxCode }}
                </el-descriptions-item>
                <el-descriptions-item label="备注">
                  {{ ruleDetail.remark || '无' }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-section">
              <h4>物流特点</h4>
              <div class="features-content">
                <el-input 
                  v-model="ruleDetail.features" 
                  type="textarea" 
                  :rows="8"
                  readonly
                  placeholder="暂无特点描述"
                />
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- 价格计算配置 -->
        <div class="info-section" style="margin-top: 24px;">
          <h4>价格计算配置</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="计算模式">
              {{ calcModeLabel(ruleDetail.calcMode) }}
            </el-descriptions-item>
          </el-descriptions>

          <!-- 首重+续重模式 -->
          <div v-if="ruleDetail.calcMode === 'first_additional'" style="margin-top: 16px;">
            <h5>首重+续重配置</h5>
            <el-descriptions :column="3" border>
              <el-descriptions-item label="首重重量">
                {{ ruleDetail.firstWeight || 0 }}G
              </el-descriptions-item>
              <el-descriptions-item label="首重价格">
                {{ ruleDetail.firstPrice || 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="首重价格(备选)">
                {{ ruleDetail.firstPriceAlt || 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="续重重量">
                {{ ruleDetail.additionalWeight || 0 }}G
              </el-descriptions-item>
              <el-descriptions-item label="续重价格">
                {{ ruleDetail.additionalPrice || 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="续重价格(备选)">
                {{ ruleDetail.additionalPriceAlt || 0 }}
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 续重模式 -->
          <div v-if="ruleDetail.calcMode === 'additional'" style="margin-top: 16px;">
            <h5>续重配置</h5>
            <el-descriptions :column="3" border>
              <el-descriptions-item label="续重重量">
                {{ ruleDetail.onlyAdditionalWeight || 0 }}G
              </el-descriptions-item>
              <el-descriptions-item label="续重价格">
                {{ ruleDetail.onlyAdditionalPrice || 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="续重价格(备选)">
                {{ ruleDetail.onlyAdditionalPriceAlt || 0 }}
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 详表模式 -->
          <div v-if="ruleDetail.calcMode === 'table'" style="margin-top: 16px;">
            <h5>价格详表</h5>
            <el-table :data="ruleDetail.tableDetail || []" border style="width: 100%;">
              <el-table-column prop="weight" label="重量(G)" width="200" />
              <el-table-column prop="price" label="价格" width="200" />
            </el-table>
          </div>
        </div>

        <!-- 操作记录 -->
        <div class="info-section" style="margin-top: 24px;">
          <h4>操作记录</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="创建时间">
              {{ formatDate(ruleDetail.createTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
              {{ formatDate(ruleDetail.updateTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="创建人">
              {{ ruleDetail.creator || '系统' }}
            </el-descriptions-item>
            <el-descriptions-item label="更新人">
              {{ ruleDetail.updater || '系统' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <div v-else class="loading-content">
        <el-empty description="规则不存在或已被删除" />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Edit, Box } from '@element-plus/icons-vue'
import type { FreightCalcMode } from '@/types/freightRule'

const route = useRoute()
const router = useRouter()

const ruleDetail = ref<any>(null)

// 计算模式标签
const calcModeLabel = (mode: FreightCalcMode) => {
  switch (mode) {
    case 'none': return '无需计算'
    case 'first_additional': return '首重+续重'
    case 'additional': return '续重'
    case 'table': return '详表'
    default: return '未知'
  }
}

// 格式化日期
const formatDate = (date?: string | Date) => {
  if (!date) return '未知'
  return new Date(date).toLocaleString('zh-CN')
}

// 返回列表
const goBack = () => {
  router.push('/settings/freight-rule')
}

// 编辑规则
const editRule = () => {
  // 跳转到列表页并传递编辑参数
  router.push({
    path: '/settings/freight-rule',
    query: { edit: route.params.id }
  })
}

// 获取规则详情
const getRuleDetail = async () => {
  const id = route.params.id as string
  if (!id) {
    ElMessage.error('规则ID不存在')
    goBack()
    return
  }

  // 从sessionStorage获取列表数据
  const listDataStr = sessionStorage.getItem('freightRuleList')
  let listData = []

  console.log('详情页 - 获取到的sessionStorage数据:', listDataStr)

  if (listDataStr) {
    try {
      listData = JSON.parse(listDataStr)
      console.log('详情页 - 解析后的数据:', listData)
    } catch (e) {
      console.error('解析列表数据失败:', e)
    }
  }

  // 如果sessionStorage中没有数据，使用默认的mock数据
  if (!listData || listData.length === 0) {
    console.log('详情页 - 使用默认mock数据')
    listData = getDefaultMockData()
  }

  console.log('详情页 - 查找ID:', id)
  console.log('详情页 - 可用数据:', listData)

  const rule = listData.find((item: any) => item.id === id)
  console.log('详情页 - 找到的规则:', rule)

  if (rule) {
    // 补充详情页需要的额外字段
    ruleDetail.value = {
      ...rule,
      createTime: rule.createTime || new Date().toLocaleString('zh-CN'),
      updateTime: rule.updateTime || new Date().toLocaleString('zh-CN'),
      creator: rule.creator || '系统',
      updater: rule.updater || '系统'
    }
    console.log('详情页 - 设置的ruleDetail:', ruleDetail.value)
  } else {
    console.error('详情页 - 未找到规则，ID:', id)
    ElMessage.error('规则不存在')
    goBack()
  }
}

// 获取默认mock数据（与列表页保持一致）
const getDefaultMockData = () => {
  return [
    {
      id: '1',
      logisticsName: 'EMS',
      logoUrl: 'https://via.placeholder.com/100x100/00A651/FFFFFF?text=EMS',
      logisticsType: '直邮',
      speed: '2~5日',
      features: '最快速，空运，有等级折扣，航空禁运品不可选',
      calcMode: 'none',
      weightLimit: 2000,
      taxCode: 'A123',
      remark: '追跡サービス・保険200万円まで',
      createTime: '2024-01-15 10:30:00',
      updateTime: '2024-01-20 14:20:00',
      creator: '管理员',
      updater: '管理员'
    },
    {
      id: '2',
      logisticsName: '航空便',
      logoUrl: 'https://via.placeholder.com/100x100/1E88E5/FFFFFF?text=航空',
      logisticsType: '直通',
      speed: '7~20日',
      features: '快速，空运，航空禁运品不可选',
      calcMode: 'first_additional',
      weightLimit: 1000,
      taxCode: 'B456',
      firstWeight: 500,
      firstPrice: 205,
      firstPriceAlt: 200,
      additionalWeight: 100,
      additionalPrice: 20,
      additionalPriceAlt: 18,
      remark: '',
      createTime: '2024-01-16 09:15:00',
      updateTime: '2024-01-21 16:45:00',
      creator: '操作员A',
      updater: '操作员B'
    },
    {
      id: '3',
      logisticsName: '可追踪小航空',
      logoUrl: 'https://via.placeholder.com/100x100/FF6B35/FFFFFF?text=小航空',
      logisticsType: '直邮',
      speed: '10~14日',
      features: '空运，适合8千元以下小包裹，航空禁运品不可选',
      calcMode: 'additional',
      weightLimit: 5000,
      taxCode: 'C789',
      onlyAdditionalWeight: 100,
      onlyAdditionalPrice: 12,
      onlyAdditionalPriceAlt: 10,
      remark: '',
      createTime: '2024-01-17 11:20:00',
      updateTime: '2024-01-22 09:30:00',
      creator: '操作员C',
      updater: '操作员C'
    },
    {
      id: '4',
      logisticsName: '船运',
      logoUrl: 'https://via.placeholder.com/100x100/4B0082/FFFFFF?text=船运',
      logisticsType: '直通',
      speed: '30~60日',
      features: '海运，适合重物/不能空运的商品',
      calcMode: 'table',
      weightLimit: 10000,
      taxCode: 'D012',
      tableDetail: [
        { weight: 500, price: 180 },
        { weight: 1000, price: 200 },
        { weight: 2000, price: 250 }
      ],
      remark: '',
      createTime: '2024-01-18 14:45:00',
      updateTime: '2024-01-23 16:15:00',
      creator: '管理员',
      updater: '操作员D'
    }
  ]
}

onMounted(() => {
  getRuleDetail()
})
</script>

<style scoped>
.freight-rule-detail {
  padding: 16px;
}

.detail-content {
  padding: 0;
}

.info-section {
  margin-bottom: 24px;
}

.info-section h4 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.info-section h5 {
  margin: 16px 0 12px 0;
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.features-content {
  height: 100%;
}

.loading-content {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-descriptions__content) {
  color: #303133;
}

:deep(.el-textarea__inner) {
  resize: none;
}
</style>
